# DarkCube X-8 Main Window

# import python general function
import wx
import time
import os
import math
import sys

# import darkcube function
import logwriter
import database
import wizard
import skin

if sys.platform == 'win32':
	dctime=time.clock
elif sys.platform == 'darwin':
	dctime=time.time
else:
	dctime=time.time



class DarkCube_version:
        def __init__(self):
                return 2.0

class Window(wx.Frame):
	def __init__(self, parent, id, title):
		print ''
		print '     starting iMolecule DarkCube X-8 . . .'
		print ''
		self.log = logwriter.writer('main.py')
		self.log.status('Loading Backend function')
		#data = database.dbconnect()
		self.log.status('Backend function successfully loaded')
		self.log.status('Loading GUI')
		self.log.status('Creating window')
		skdatatemp = skin.sheet()
		self.skdata=skdatatemp.getdata()
		# create window
		wx.Frame.__init__(self, parent, id, title, size=(self.skdata['window']['width'], self.skdata['window']['height']),style=wx.FRAME_NO_TASKBAR | wx.NO_BORDER | wx.STAY_ON_TOP)
        
		#Internal Data
		self.elapsedtime = 0
		self.timerstatus = 0
		self.timer = wx.Timer(self,-1)
		self.timerfont = wx.Font(self.skdata['timing']['size'], wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_BOLD, False, self.skdata['timing']['fface'])
		self.keypressed=[]
		if sys.platform == 'win32':
			self.secmulti=100
		elif sys.platform == 'darwin':
			self.secmulti=100
		
		self.log.status('Binding event')
		#Event Binding
		self.Bind(wx.EVT_PAINT, self.OnPaint)
		self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
		self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
		self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
		self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
		self.Bind(wx.EVT_MOTION, self.OnMouseMove)
		self.Bind(wx.EVT_TIMER,self.update)
		self.log.status('Displaying Window')
		#Showing
		self.Centre()
		self.Show(True)
	def OnPaint(self, event):
		self.log.status('Painting Window')
		self.dc = wx.PaintDC(self)
		brush = wx.BrushFromBitmap(wx.Bitmap(self.skdata['window']['background']))
		self.dc.SetBrush(brush)
		self.dc.DrawRectangle(0, 0, self.skdata['window']['width'], self.skdata['window']['height'])
		self.painttime(0)
		#self.paintscramble()
		#self.paintprofile()
		#self.painthint()
		self.log.status('GUI successfully loaded')
	def update(self,e):
		self.elapsedtime = math.floor(dctime()*self.secmulti) - self.start
		self.painttime(int(self.elapsedtime))
		#self.log.error(str(self.elapsedtime))
	def painttime(self,intCentisecond):
		#self.dc.Clear()
		brush = wx.BrushFromBitmap(wx.Bitmap(self.skdata['window']['background']))
		self.dc.SetBrush(brush)
		self.dc.DrawRectangle(0, 0, self.skdata['window']['width'], self.skdata['window']['theight'])
		self.dc.SetFont(self.timerfont)
		self.dc.SetPen(wx.Pen('#000000'))
		self.dc.SetTextForeground(self.skdata['timing']['color'])
		self.dc.DrawText(self.CS2str(intCentisecond),self.skdata['timing']['x'],self.skdata['timing']['y'])
	def CS2str(self,CS):
		minute = math.floor(CS/6000)
		second = CS%6000
		csecond = second%100
		second = math.floor(second/100)
		return self.it2str(minute)+' : '+self.it2str(second)+' . '+self.it2str(csecond)
	def it2str(self,intC):
		if intC==0:
			return '00'
		elif intC<10:
			return '0'+str(int(intC))
		else:
			return str(int(intC))
	def OnLeftDown(self, event):
		pos = event.GetPosition()
		x, y = self.ClientToScreen(event.GetPosition())
		ox, oy = self.GetPosition()
		dx = x - ox
		dy = y - oy
		self.delta = ((dx, dy))
	def OnMouseMove(self, event):
		if event.Dragging() and event.LeftIsDown():
			x, y = self.ClientToScreen(event.GetPosition())
			fp = (x - self.delta[0], y - self.delta[1])
			self.Move(fp)
	def OnRightDown(self, event):
		#self.Close()
		#self.start = math.floor(dctime()*100)
		#self.timer.Start(50)
		pass
	# KeyNote ( not iWork )
	""" 
	   32 = space       [D,U] start stop timer
	   27 = esc         [U]   exit
	   80 = p           [U]   choose profile
	   83 = s           [U]   settings 
	   13 = enter       [D]   save score
	   16 = shift       [D]   (with enter) +2 and save score
	   8 = bksp         [D]   discard score
	   112 = F1         [U]   help
	   38 = up arrow    [U]   generate scramble
	   35 = end         [U]   empty profile
	   45 = insert      [U]   new profile
	   46 = delete      [U]   delete profile
	"""
	def OnKeyDown(self,event):
		key=event.GetUnicodeKey()
		if self.keypressed.count(key)==0:
			self.keypressed.append(key)
			if key==32:
				self.timer_pre()
			elif key==27:
				if self.timerstatus==0:
					self.Close()
					sys.exit()
			elif key==13:
				self.timer_clear()
	def OnKeyUp(self,event):
		key=event.GetUnicodeKey()
		if self.keypressed.count(key)==1:
			self.keypressed.remove(key)
			if key==32:
				self.timer_post()
	
	def timer_pre(self):
		if self.timerstatus==1:
			# stop timer
			self.timer.Stop()
			self.update(self)
			self.timerstatus = 2
	def timer_post(self):
		if self.timerstatus==0:
			self.timerstatus=1
			self.start = math.floor(dctime()*self.secmulti)
			self.timer.Start(50)
	def timer_clear(self):
		if self.timerstatus==2:
			self.painttime(0)
			self.timerstatus=0
		

if __name__ == '__main__':
	app = wx.App(redirect=0)
	Window(None, -1, 'DarkCube')
	app.MainLoop()
